let glob = require('glob');
let path = require('path');
let fs = require('fs');

const replaceM = (content,root) => {
    let M = [
        [`src="` + root,`src="`],
        [`src='` + root,`src='`],
        [`href="` + root,`href="`],
        [`href='` + root,`href='`],
    ];
    M.forEach(m => {
        let index = content.indexOf(m[0]);
        while (index !== -1) {
            content = content.replace(m[0],m[1]);
            index = content.indexOf(m[0]);
        }
    });
    return content;
};
// 将路径替换为 相对路径
// 例如
//      root='/'                        src="/a.js" => src='a.js'
//      root='http://www.abc.com/'      src="http://www.abc.com/a.js" => src="a.js"
// root
function replace(filePath,root) {
    glob(filePath,function (err,file) {
        if (err) {
            throw err;
        } else {
            file.forEach(_ => {
                if (_.endsWith('.html') || _.endsWith('.htm')) {
                    let fileContent = fs.readFileSync(_,'utf-8');
                    fs.writeFileSync(_,replaceM(fileContent,root),'utf-8');
                }
            });
        }
    });
}

replace("C:\\Users\\IBAS\\Downloads\\t\\www.moe.gov.cn","./")